package com.supercwn.player.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.supercwn.player.R;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;


/**
 * 项目名称：phonePlayer
 * 类描述：
 * 创建人：TianGenhu
 * 创建时间：2017/10/31 14:58
 * 修改人：TianGenhu
 * 修改时间：2017/10/31 14:58
 * 修改备注：
 */

public class YuanShengSurfaceViewActivity extends Activity implements MediaPlayer.OnPreparedListener, View.OnClickListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnInfoListener {
    private String path1 = "http://192.168.3.214:8112/MP4/34a014ca1fa846bbb5d6776919cb47e8/index.mp4?AuthInfo=vdNn0nS2ob5PU%2Fxn88AfmWaMrbljMFru8edlX7Jha4aqP4B%2BQmT2BCbgZQN%2BefNMKEz7vJH38g79%0Ax81XgsPxrfnsw%2FSFGA2i8%2Fp89aICYpPglyyPyokiUWF5%2Bd9ZaUrpHmY%2FGi0KTKitlPD2sqAtOg%3D%3D%0A&version=3";
    private String path = "http://baobab.wandoujia.com/api/v1/playUrl?vid=2614&editionType=normal";

    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private MediaPlayer mediaPlayer;
    private ProgressBar progressBar;
    private int playPosition = 1000;
    private SeekBar seekBar;
    private String videoTimeString;
    private TextView vedioTiemTextView;
    private Button replayButton;
    private Button playButton;
    private Button screenShotButton;
    private boolean seekBarAutoFlag;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yuan_sheng_surface_view_activity);
        initData();
        initView();
    }

    private void initData() {
        path = getIntent().getStringExtra("url");
    }

    private void initView() {
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        // 设置surfaceHolder
        surfaceHolder = surfaceView.getHolder();
        // 设置Holder类型,该类型表示surfaceView自己不管理缓存区,虽然提示过时，但最好还是要设置
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // 设置surface回调
        surfaceHolder.addCallback(new SurfaceCallback());
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        seekBar = (SeekBar) findViewById(R.id.seekbar);
        vedioTiemTextView = (TextView) findViewById(R.id.textView_showTime);
        replayButton = (Button) findViewById(R.id.button_replay);
        playButton = (Button) findViewById(R.id.button_play);
        screenShotButton = (Button) findViewById(R.id.button_screenShot);
        findViewById(R.id.button_start).setOnClickListener(this);
    }

    // SurfaceView的callBack
    private class SurfaceCallback implements SurfaceHolder.Callback {
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // SurfaceView的大小改变
        }

        public void surfaceCreated(SurfaceHolder holder) {
            // surfaceView被创建
            // 设置播放资源
            playVideo();
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // surfaceView销毁
            // 如果MediaPlayer没被销毁，则销毁mediaPlayer
            if (null != mediaPlayer) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }
    }

    /**
     * 播放视频
     */
    public void playVideo() {
        // 初始化MediaPlayer
        mediaPlayer = new MediaPlayer();
        // 重置mediaPaly,建议在初始滑mediaplay立即调用。
        mediaPlayer.reset();
        // 设置声音效果
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        // 设置播放完成监听
        mediaPlayer.setOnCompletionListener(this);
        // 设置媒体加载完成以后回调函数。
        mediaPlayer.setOnPreparedListener(this);
        // 错误监听回调函数
        mediaPlayer.setOnErrorListener(this);
        // 设置缓存变化监听
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnInfoListener(this);
        Uri uri = Uri.parse(path);
        try {
            // mediaPlayer.reset();
            mediaPlayer.setDataSource(YuanShengSurfaceViewActivity.this, uri);
            // 设置异步加载视频，包括两种方式 prepare()同步，prepareAsync()异步
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.i("TGH", "视频播放完成");
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        Log.i("TGH", "视频出错了  ：" + what + "  " + extra);
        return false;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        Log.i("TGH", "视频开始缓冲   " + percent);

    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        if (what == 701) {
            progressBar.setVisibility(View.VISIBLE);
        } else if (what == 702) {
            progressBar.setVisibility(View.GONE);
        }
        return false;
    }

    /**
     * 视频加载完毕监听
     *
     * @param mp
     */
    @Override
    public void onPrepared(MediaPlayer mp) {
        // 当视频加载完毕以后，隐藏加载进度条
        progressBar.setVisibility(View.GONE);
        // 判断是否有保存的播放位置,防止屏幕旋转时，界面被重新构建，播放位置丢失。
        if (playPosition >= 0) {
            mediaPlayer.seekTo(playPosition);
            playPosition = -1;
            // surfaceHolder.unlockCanvasAndPost(Constants.getCanvas());
        }
        // 播放视频
        mediaPlayer.start();
        // 设置显示到屏幕
        mediaPlayer.setDisplay(surfaceHolder);
        // 设置surfaceView保持在屏幕上
        mediaPlayer.setScreenOnWhilePlaying(true);
        surfaceHolder.setKeepScreenOn(true);
        // 设置控制条,放在加载完成以后设置，防止获取getDuration()错误
        seekBar.setProgress(0);
        seekBar.setMax(mediaPlayer.getDuration());
        // 设置播放时间
        videoTimeString = getShowTime(mediaPlayer.getDuration());
        vedioTiemTextView.setText("00:00:00/" + videoTimeString);
        // 设置拖动监听事件
        seekBar.setOnSeekBarChangeListener(new SeekBarChangeListener());
        // 设置按钮监听事件
        // 重新播放
        replayButton.setOnClickListener(this);
        // 暂停和播放
        playButton.setOnClickListener(YuanShengSurfaceViewActivity.this);
        // 截图按钮
        screenShotButton.setOnClickListener(YuanShengSurfaceViewActivity.this);
        seekBarAutoFlag = true;
        // 开启线程 刷新进度条
        thread.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_replay://重新播放
                mediaPlayer.seekTo(0);
                mediaPlayer.start();
                break;
            case R.id.button_play://播放
                mediaPlayer.pause();
                break;
            case R.id.button_screenShot:
                mediaPlayer.start();
                break;
            case R.id.button_start:
                mediaPlayer.start();
                break;
            default:
                break;
        }
    }

    /**
     * 滑动条变化线程
     */
    private Thread thread = new Thread() {

        public void run() {
            // TODO Auto-generated method stub
            super.run();
            // 增加对异常的捕获，防止在判断mediaPlayer.isPlaying的时候，报IllegalStateException异常
            try {
                while (seekBarAutoFlag) {
                       /*
                        * mediaPlayer不为空且处于正在播放状态时，使进度条滚动。
                        * 通过指定类名的方式判断mediaPlayer防止状态发生不一致
                        */

                    if (null != YuanShengSurfaceViewActivity.this.mediaPlayer
                            && YuanShengSurfaceViewActivity.this.mediaPlayer.isPlaying()) {
                        seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * seekBar拖动监听类
     *
     * @author shenxiaolei
     */
    @SuppressWarnings("unused")
    private class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // TODO Auto-generated method stub
            if (progress >= 0) {
                // 如果是用户手动拖动控件，则设置视频跳转。
                if (fromUser) {
                    mediaPlayer.seekTo(progress);
                }
                // 设置当前播放时间
                vedioTiemTextView.setText(getShowTime(progress) + "/" + videoTimeString);
            }
        }

        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }
    }

    /**
     * 转换播放时间
     *
     * @param milliseconds 传入毫秒值
     * @return 返回 hh:mm:ss或mm:ss格式的数据
     */
    @SuppressLint("SimpleDateFormat")
    public String getShowTime(long milliseconds) {
        // 获取日历函数
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        SimpleDateFormat dateFormat = null;
        // 判断是否大于60分钟，如果大于就显示小时。设置日期格式
        if (milliseconds / 60000 > 60) {
            dateFormat = new SimpleDateFormat("hh:mm:ss");
        } else {
            dateFormat = new SimpleDateFormat("mm:ss");
        }
        return dateFormat.format(calendar.getTime());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
